package com.example.its2021606134chh.TLModule;

import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.its2021606134chh.ETCModule.Cars;
import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.ThresholdModule.ThresholdParams;
import com.example.its2021606134chh.ThresholdModule.ThresholdRoad;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TLMFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TLMFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Spinner spTLM;
    private Button btnTLMQuery;
    private Button btnTLMBatchSet;
    private RecyclerView rvTLMList;
    private List<Lights> list = new ArrayList<>();
    private int[] roadList = {1, 2, 3, 4, 5};   //车辆列表

    public TLMFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TLMFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TLMFragment newInstance(String param1, String param2) {
        TLMFragment fragment = new TLMFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_t_l_m, container, false);
        spTLM = (Spinner) view.findViewById(R.id.spTLM);
        btnTLMQuery = (Button) view.findViewById(R.id.btnTLMQuery);
        btnTLMBatchSet = (Button) view.findViewById(R.id.btnTLMBatchSet);
        rvTLMList = (RecyclerView) view.findViewById(R.id.rvTLMList);
        rvTLMList.setLayoutManager(new LinearLayoutManager(getContext()));
        initData();
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (TLightsRViewAdapter.getIsButton()) {
                    TLightsRViewAdapter.setIsButton(false);
                    initData();
                }
            }
        };
        timer.schedule(timerTask, 0, 1000);
        btnTLMQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
        btnTLMBatchSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<Integer, Boolean> checkStatus = TLightsRViewAdapter.getCheck();
                ArrayList<String> roods = new ArrayList<>();
                for (Map.Entry<Integer, Boolean> entry : checkStatus.entrySet()) {
                    Log.i("TAG", "Key = " + entry.getKey() + ", Value = " + entry.getValue());
                    if (entry.getValue()) {
                        roods.add(String.valueOf(entry.getKey() + 1));
                    }
                }
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_tlmrv_dialog,null,false);
                dialog.setView(view);
                Button btnTLMDiaCancel = (Button)view.findViewById(R.id.btnTLMDiaCancel);
                EditText edtRedTime = (EditText)view.findViewById(R.id.edtRedTime);
                EditText edtYellowTime = (EditText)view.findViewById(R.id.edtYellowTime);
                EditText edtGreenTime = (EditText)view.findViewById(R.id.edtGreenTime);
                Button btnTLMDiaSave = (Button)view.findViewById(R.id.btnTLMDiaSave);
                AlertDialog mdialog = dialog.show();
                btnTLMDiaSave.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        String rood = String.valueOf(position + 1);
                        String sRed = edtRedTime.getText().toString().trim();
                        String sYellow = edtYellowTime.getText().toString().trim();
                        String sGreen = edtGreenTime.getText().toString().trim();
                        for (String rood : roods) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                        @Override
                                        public void onFailure(Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String json) {
                                            TLightsRViewAdapter.setIsButton(true);
                                            String msg;
                                            Log.i("TAG", json);
                                            Gson gson = new Gson();
                                            mdialog.dismiss();
                                            TLMResult result = gson.fromJson(json, TLMResult.class);
                                            String RESULT = result.getRESULT();
                                            if (RESULT.equals("S")) {
                                                mdialog.dismiss();
//                                        向数据库传入数据
                                                msg = rood + "路口设置成功\n" + "红灯:" + sRed + "秒\n" + "黄灯:" + sYellow + "秒\n" + "绿灯:" + sGreen + "秒";
                                                Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                                            } else {
                                                mdialog.dismiss();
                                                msg = rood + "路口设置失败";
                                                Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }, "set_trafficlight_config", new String[]{"TrafficLightId", "RedTime", "GreenTime", "YellowTime", "UserName"}, rood, sRed, sGreen, sYellow, "user1");
                                }
                            }).start();
                        }
                    }
                });

                btnTLMDiaCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mdialog.dismiss();
                    }
                });
            }
        });
        return view;
    }

    public void initData() {
        list.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int roadId : roadList) {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            TlmLights lights = gson.fromJson(json, TlmLights.class);
                            int redTime = lights.getRedTime();
                            int yellowTime = lights.getYellowTime();
                            int greenTime = lights.getGreenTime();
                            list.add(new Lights(roadId, redTime, yellowTime, greenTime));
//                            Log.i("TAG",  roadId + " " + redTime + " " + yellowTime + " " + greenTime);
                            String s = spTLM.getSelectedItem().toString();
                            switch (s) {
                                case "路口升序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getRoad() > l2.getRoad()) {
                                                return 1;
                                            } else if (l1.getRoad() < l2.getRoad()){
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "路口降序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getRoad() > l2.getRoad()) {
                                                return -1;
                                            } else if (l1.getRoad() < l2.getRoad()){
                                                return 1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "红灯升序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getRedLight() > l2.getRedLight()) {
                                                return 1;
                                            } else if (l1.getRedLight() < l2.getRedLight()){
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "红灯降序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getRedLight() > l2.getRedLight()) {
                                                return -1;
                                            } else if (l1.getRedLight() < l2.getRedLight()){
                                                return 1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "绿灯升序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getGreenLight() > l2.getGreenLight()) {
                                                return 1;
                                            } else if (l1.getGreenLight() < l2.getGreenLight()){
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "绿灯降序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getGreenLight() > l2.getGreenLight()) {
                                                return -1;
                                            } else if (l1.getGreenLight() < l2.getGreenLight()){
                                                return 1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "黄灯升序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getYellowLight() > l2.getYellowLight()) {
                                                return 1;
                                            } else if (l1.getYellowLight() < l2.getYellowLight()){
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                                case "黄灯降序":
                                    Collections.sort(list, new Comparator<Lights>() {
                                        @Override
                                        public int compare(Lights l1, Lights l2) {
                                            if (l1.getYellowLight() > l2.getYellowLight()) {
                                                return -1;
                                            } else if (l1.getYellowLight() < l2.getYellowLight()){
                                                return 1;
                                            }
                                            return 0;
                                        }
                                    });
                                    break;
                            }

                            rvTLMList.setAdapter(new TLightsRViewAdapter(list, getContext()));
                        }
                    }, "get_trafficlight_config", new String[]{"TrafficLightId", "UserName"}, roadId, "user1");
                }
            }
        }).start();
    }

}